package com.roadjava.rbac.controller;

import com.roadjava.rbac.bean.entity.FavoriteDO;
import com.roadjava.rbac.bean.entity.FavoriteEQ;
import com.roadjava.rbac.bean.res.Result;
import com.roadjava.rbac.security.RateLimitService;
import com.roadjava.rbac.service.FavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/favorites")
public class FavoriteController {

    @Autowired
    private FavoriteService favoriteService;

    // 引入 RateLimitService
    private final RateLimitService rateLimitService = new RateLimitService();

    @PostMapping
    public Result<FavoriteEQ> addFavorite(@RequestBody FavoriteEQ favorite) {
        String userId = favorite.getId().toString();
        // 假设 FavoriteEQ 中有用户 ID
        if (!rateLimitService.isAllowed(userId)) {
            return Result.buildFailure("Too Many Requests");
        }

        favoriteService.addFavorite(favorite);
        return Result.buildSuccess(favorite);
    }

    @DeleteMapping
    public Result<Void> removeFavorite(@RequestParam Long resourceId, @RequestParam Long Id) {
        String userId = Id.toString();
        // 假设通过 Id 获取用户 ID
        if (!rateLimitService.isAllowed(userId)) {
            return Result.buildFailure("Too Many Requests");
        }

        favoriteService.removeFavoriteByResourceAndUser(resourceId, Id);
        return Result.buildSuccess(null);
    }

    @GetMapping("/{userId}")
    public Result<List<FavoriteDO>> getUserFavorites(@PathVariable Long userId) {
        List<FavoriteDO> favorites = favoriteService.getUserFavorites(userId);
        return Result.buildSuccess(favorites);
    }

    @GetMapping("/count")
    public Result<Long> getFavoriteCount(@RequestParam Long resourceId) {
        Long count = favoriteService.getFavoriteCount(resourceId);
        return Result.buildSuccess(count);
    }

    @DeleteMapping("/resource")
    public Result<Void> removeFavoritesByResource(@RequestParam Long resourceId) {
        if (!rateLimitService.isAllowed(resourceId.toString())) {
            return Result.buildFailure("Too Many Requests");
        }

        favoriteService.removeFavoritesByResource(resourceId);
        return Result.buildSuccess(null);
    }

    @GetMapping("/status")
    public Result<Boolean> getFavoriteStatus(@RequestParam Long resourceId, @RequestParam Long Id) {
        boolean isFavorited = favoriteService.isFavoritedByUser(resourceId, Id);
        return Result.buildSuccess(isFavorited);
    }
}
